//
//  NetWorkTool.swift
//  todaySwift
//
//  Created by ChokWah on 2018/3/10.
//  Copyright © 2018年 ChokWah. All rights reserved.
//

import Foundation
import Alamofire
import SwiftyJSON

protocol NetWorkToolProtocol {
    
    // // ============================== 首页 ==============================
        // 首页顶部新闻标题数据
        static func loadHomeNewsTitleData(completionHandler: @escaping (_ sections: [HomeNewsTitle]) -> ())

        // ============================== 我的 mine ==============================
        // 我的界面，cell的数据
        static func loadMyCellData(completionHandler: @escaping (_ sections: [[MyCellModel]]) -> ())
        // 我的关注数据
        static func loadMyConcern(completionHandler: @escaping (_ sections: [MyConcern]) -> ())
        // 用户详情数据
        static func loadUserDetail(user_id: Int, completionHandler: @escaping (_ userDetail: UserDetail) -> ())
        // 已关注用户，取消关注
        static func relationUnfollow(user_id: Int, completionHandler: @escaping (_ concernUser: ConcernUser) -> ())
        // 点击关注用户
        static func relationFollow(user_id: Int, completionHandler: @escaping (_ concernUser: ConcernUser) -> ())
        // 关注用户后的相关推荐
        static func supplementRecommends(user_id: Int, completionHandler: @escaping (_ concerns: [UserCard]) -> ())
        // 获取用户详情动态列表数据
        static func loadUserDetailDongtaiList(user_id: Int, completionHandler: @escaping (_ dongtais: [UserDetailDongtai]) -> ())
}

// 在协议的拓展里面写方法实现
extension NetWorkToolProtocol {
    // MARK: 首页顶部新闻标题数据
    static func loadHomeNewsTitleData(completionHandler: @escaping (_ sections: [HomeNewsTitle]) -> ()) {
        // 拼接完整请求
        let url = BASE_URL + "/article/category/get_subscribed/v1/?"
        let params = ["device_id" : device_id, "iid": iid]
        Alamofire.request(url, parameters: params).responseJSON { (response) in
            guard response.result.isSuccess else {
                return // 此时可以做error处理
            }
            if let value = response.result.value {
                let json = JSON(value)
                guard json["message"] == "success" else {
                    return
                }
                if let dataDict = json["data"].dictionary {
                    if let datas = dataDict["data"]?.arrayObject {
                        var titles = [HomeNewsTitle]()
                        let jsonString = "{\"category\":\"\", \"name\":\"推荐\"}"
                        titles.append(HomeNewsTitle.deserialize(from: jsonString)!)
                        titles += datas.flatMap({ HomeNewsTitle.deserialize(from: $0 as! Dictionary)  })
                        completionHandler(titles)
                    }
                }
            }
        }
    }

    // MARK: 我的界面，cell的数据
    static func loadMyCellData(completionHandler: @escaping (_ sections: [[MyCellModel]]) -> ()) {
        
        // 拼接完整请求
        let url = BASE_URL + "/user/tab/tabs/?"
        let params = ["device_id" : device_id]
        Alamofire.request(url, parameters: params).responseJSON { (response) in
            guard response.result.isSuccess else {
                return // 此时可以做error处理
            }
            if let value = response.result.value {
                let json = JSON(value)
                guard json["message"] == "success" else {
                    return
                }
                if let data = json["data"].dictionary {
//                    print(data)
                    if let sections = data["sections"]?.arrayObject {
                        completionHandler(
                            sections.flatMap({ item in
                            (item as! [Any]).flatMap({ row in
                                MyCellModel.deserialize(from: row as! NSDictionary)
                            })
                        }))
                    }
                }
            }
        }
    }
    // MARK: 我的关注数据
    static func loadMyConcern(completionHandler: @escaping (_ sections: [MyConcern]) -> ()) {
        
        // 拼接完整请求
        let url = BASE_URL + "/concern/v2/follow/my_follow/??"
        let params = ["device_id" : device_id]
        Alamofire.request(url, parameters: params).responseJSON { (response) in
            guard response.result.isSuccess else {
                return // 此时可以做error处理
            }
            if let value = response.result.value {
                let json = JSON(value)
                guard json["message"] == "success" else {
                    return
                }
                if let data = json["data"].arrayObject {
                    print(data)
                    var rows = [MyConcern]()
                    completionHandler(data.flatMap({
                        MyConcern.deserialize(from: $0 as? NSDictionary)
                    }))
                }
            }
        }
    }
    
    // MARK: 获取用户详情数据
    static func loadUserDetail(user_id: Int, completionHandler: @escaping (_ userDetail: UserDetail) -> ()) {
        
        // 拼接完整请求
        let url = BASE_URL + "/user/profile/homepage/v4/?"
        let params = ["user_id": user_id,
                            "device_id" : device_id,
                            "iid": iid]
        Alamofire.request(url, parameters: params).responseJSON { (response) in
            guard response.result.isSuccess else {
                return // 此时可以做error处理
            }
            if let value = response.result.value {
                let json = JSON(value)
                guard json["message"] == "success" else {
                    return
                }
                if let data = json["data"].arrayObject {
                    let userDetail = UserDetail.deserialize(from: data as? NSDictionary)
                    completionHandler(userDetail!)
                }
            }
        }
    }
    
    // 每天取消关注只能30次
    // MARK: 已关注用户，取消关注
    static func relationUnfollow(user_id: Int, completionHandler: @escaping (_ concernUser: ConcernUser) -> ()) {
        
        // 拼接完整请求
        let url = BASE_URL + "/2/relation/unfollow/?"
        let params = ["user_id": user_id,
                      "device_id" : device_id,
                      "iid": iid]
        Alamofire.request(url, parameters: params).responseJSON { (response) in
            guard response.result.isSuccess else {
                return // 此时可以做error处理
            }
            if let value = response.result.value {
                let json = JSON(value)
                guard json["message"] == "success" else { // 这里做error处理
                    return
                }
                if let data = json["data"].dictionaryObject {
                    let user = ConcernUser.deserialize(from: data["user"] as? NSDictionary)
                    completionHandler(user!)
                }
            }
        }
    }

    // MARK: 点击关注用户
    static func relationFollow(user_id: Int, completionHandler: @escaping (_ concernUser: ConcernUser) -> ()) {
        
        // 拼接完整请求
        let url = BASE_URL + "/2/relation/unfollow/?"
        let params = ["user_id": user_id,
                      "device_id" : device_id,
                      "iid": iid]
        Alamofire.request(url, parameters: params).responseJSON { (response) in
            guard response.result.isSuccess else {
                return // 此时可以做error处理
            }
            if let value = response.result.value {
                let json = JSON(value)
                guard json["message"] == "success" else { // 这里做error处理
                    return
                }
                if let data = json["data"].dictionaryObject {
                    let user = ConcernUser.deserialize(from: data["user"] as? NSDictionary)
                    completionHandler(user!)
                }
            }
        }
    }
    
    // MARK: 关注用户后的相关推荐
    static func supplementRecommends(user_id: Int, completionHandler: @escaping (_ concerns: [UserCard]) -> ()) {
        
        // 拼接完整请求
        let url = BASE_URL + "/user/relation/user_recommend/v1/supplement_recommends/?"
        let params = ["device_id" : device_id,
                      "follow_user_id": user_id,
                      "iid": iid,
                      "scene":"follow",
                      "source":"follow"] as [String : Any]
        Alamofire.request(url, parameters: params).responseJSON { (response) in
            guard response.result.isSuccess else {
                return // 此时可以做error处理
            }
            if let value = response.result.value {
                let json = JSON(value)
                guard json["err_no"] == 0 else { // 这里做error处理
                    return
                }
                if let user_cards = json["user_cards"].arrayObject {
                    completionHandler(user_cards.flatMap({
                        UserCard.deserialize(from: $0 as? NSDictionary)
                    }))
                }
            }
        }
    }
    
    // MARK: 获取用户详情动态列表数据
    static func loadUserDetailDongtaiList(user_id: Int, completionHandler: @escaping (_ dongtais: [UserDetailDongtai]) -> ()) {
        // 拼接完整请求
        let url = BASE_URL + "/dongtai/list/v15/?"
        let params = ["user_id" : user_id]
        Alamofire.request(url, parameters: params).responseJSON { (response) in
            guard response.result.isSuccess else {
                return // 此时可以做error处理
            }
            if let value = response.result.value {
                let json = JSON(value)
                guard json["err_no"] == 0 else { // 这里做error处理
                    return
                }
                if let data = json["data"].dictionary {
                    if let datas = data["data"]?.arrayObject {
                        completionHandler(datas.flatMap({
                            UserDetailDongtai.deserialize(from: $0 as? NSDictionary)
                        })) 
                    }
                }
            }
        }
    }
    
    // MARK: 获取用户详情文章列表数据
    static func loadUserDetailArticleList(user_id: Int, completionHandler: @escaping (_ dongtais: [UserDetailDongtai]) -> ()) {
        // 拼接完整请求
        let url = BASE_URL + "/pgc/ma/?"
        let params = ["user_id" : user_id,
                            "page_type": 1,
                            "media_id": user_id,
                            "output": "json",
                            "is_json": 1,
                            "from": "user_profile_app",
                            "version": 2,
                            "as": "a2c5ad8d64e3fa47612848", //这个是变化的，根据时间变化
                            "cp": ""] as [String : Any]
        Alamofire.request(url, parameters: params).responseJSON { (response) in
            guard response.result.isSuccess else {
                return // 此时可以做error处理
            }
            if let value = response.result.value {
                let json = JSON(value)
                guard json["err_no"] == 0 else { // 这里做error处理
                    print("获取用户详情文章 error: \(json)")
                    return
                }
                if let data = json["data"].arrayObject {
                    completionHandler(data.flatMap({
                        UserDetailDongtai.deserialize(from: $0 as? NSDictionary)
                    }))
                }
            }
        }
    }
}

struct NetWorkTool : NetWorkToolProtocol {
    
}
